package algorithm_demo.leetcode;

import javax.security.auth.login.CredentialException;
import java.util.LinkedList;
import java.util.List;

/**
 * 111. 二叉树的最小深度
 * <a href="https://leetcode.cn/problems/minimum-depth-of-binary-tree/">https://leetcode.cn/problems/minimum-depth-of-binary-tree/</a>
 *
 * @author Api
 * @date 2023/5/7 0:44
 */
public class Problem_111_MinimumDepthOfBinaryTree {


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //深度搜索1
    int min = 0;
    public int minDepth1(TreeNode root) {

        int start = 0;
        dfs(root, start);
        return min;
    }

    public void dfs(TreeNode node,int deep) {
        //终止条件
        if (node == null) {
            return;
        }
        //更新当前结果deep
        deep++;
        //若到达末尾叶子节点，进行最优结果更新
        if (node.left == null && node.right == null) {
            if (deep < min || min == 0) {
                min = deep;
            }
        }
        //左右子树递归
        dfs(node.left,  deep);
        dfs(node.right, deep);
    }
    //深度搜索2
    public int minDepth2(TreeNode root) {
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        int deep = Integer.MAX_VALUE;
        if (root.left != null){
            deep = Math.min(minDepth2(root.left), deep);
        }
        if (root.right != null){
            deep = Math.min(minDepth2(root.right), deep);
        }
        return deep+1;
    }
    //按层遍历
    public int minDepth3(TreeNode root) {
        if (root == null){
            return 0;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);
        for(int i = 1; !list.isEmpty(); ++i){
            int count = list.size();
            while (count-- > 0) {
                TreeNode node = list.removeFirst();
                //第一个叶子节点所在的层数就是最小深度
                if (node.left == null && node.right == null) {
                    return i;
                }
                if (node.left != null) {
                    list.add(node.left);
                }
                if (node.right != null) {
                    list.add(node.right);
                }
            }
        }
        return -1;
    }

}
